package xyz.xtt.pay.utils.pay;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @author zhangcj
 * @date 2025/2/5 14:05
 */
public class RSASignature {


    public static String privateKeyToString(PrivateKey privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpec = keyFactory.getKeySpec(privateKey, PKCS8EncodedKeySpec.class);
        byte[] encodedKey = keySpec.getEncoded();
        return Base64.getEncoder().encodeToString(encodedKey);
    }

    public static String sign(String data, String base64PrivateKey) throws Exception {
        Signature signature = Signature.getInstance("SHA256withRSA");
        PrivateKey privateKey = stringToPrivateKey(base64PrivateKey);
        signature.initSign(privateKey);
        signature.update(data.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(signature.sign());
    }


    public static byte[] sign(String data, PrivateKey privateKey) throws Exception {
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(data.getBytes("UTF-8"));
        return signature.sign();
    }

    public static boolean verify(String data, byte[] signatureBytes, PublicKey publicKey) throws Exception {
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initVerify(publicKey);
        signature.update(data.getBytes("UTF-8"));
        return signature.verify(signatureBytes);
    }

    public static PublicKey stringToPublicKey(String base64PublicKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(base64PublicKey);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA"); // 或者 "EC" 根据你的公钥类型
        return kf.generatePublic(spec);
    }

    public static PrivateKey stringToPrivateKey(String base64PrivateKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(base64PrivateKey);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA"); // 或者 "EC", "DSA" 根据你的私钥类型
        return kf.generatePrivate(spec);
    }


    public static boolean verify(String data, byte[] signatureBytes, String base64PublicKey) throws Exception {
        Signature signature = Signature.getInstance("SHA256withRSA");
        PublicKey publicKey = stringToPublicKey(base64PublicKey);
        signature.initVerify(publicKey);
        signature.update(data.getBytes("UTF-8"));
        return signature.verify(signatureBytes);
    }
}
